//
//  QRCodeViewController.m
//  HuLaQuan
//
//  Created by hok on 1/22/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "QRCodeViewController.h"

#import "UIView+SDExtension.h"

#import <AVFoundation/AVFoundation.h>

#import "ScanPayViewController.h"

#import "ZCTradeView.h"

//Logic Modal
#import "ScanPayEngine.h"
#import "VerifyPayPasswordEngine.h"
#import "GetUserAccountInfoEngine.h"
#import "GetUserDetailInfoEngine.h"


//Jump To

#import "ScanPayFinishInfoController.h"

@interface QRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate,ScanPayViewDelegate,ZCTradeViewDelegate>

@property (nonatomic, strong) AVCaptureSession *session;

@property (nonatomic, weak) UIView *maskView;

@property (nonatomic,strong) ZCTradeView *tradeView;

@property (nonatomic, strong) ScanPayEngine *scanPayEngine;
@property (nonatomic, strong) VerifyPayPasswordEngine *verifyPayPasswordEngine;
@property (nonatomic,strong) GetUserAccountInfoEngine *getUserAccountInfoEngine;

@property (nonatomic, strong) GetUserDetailInfoEngine *getUserDetailInfoEngine;

@property (nonatomic, strong) NSDictionary *paymentFinishInfo;

@end

@implementation QRCodeViewController

static const CGFloat kScanWindowW = 220;
static const CGFloat kScanWindowY = 50.0;

- (GetUserDetailInfoEngine *)getUserDetailInfoEngine
{
    if (!_getUserDetailInfoEngine) {
        _getUserDetailInfoEngine = [[GetUserDetailInfoEngine alloc] init];
    }
    return _getUserDetailInfoEngine;
}
- (ScanPayEngine *)scanPayEngine
{
    if (!_scanPayEngine) {
        _scanPayEngine = [[ScanPayEngine alloc] init];
    }
    return _scanPayEngine;
}
- (VerifyPayPasswordEngine *)verifyPayPasswordEngine
{
    if (!_verifyPayPasswordEngine) {
        _verifyPayPasswordEngine = [[VerifyPayPasswordEngine alloc] init];
    }
    return _verifyPayPasswordEngine;
}
- (GetUserAccountInfoEngine *)getUserAccountInfoEngine
{
    if (!_getUserAccountInfoEngine) {
        _getUserAccountInfoEngine = [[GetUserAccountInfoEngine alloc] init];
    }
    return _getUserAccountInfoEngine;
}
- (void)setupUI
{
    self.view.clipsToBounds = YES;
    
    [self setupMaskView];
    
    // [self setupBottomBar];
    
    [self setupScanWindowView];
    
    [self beginScanning];
    
    self.title = @"扫描二维码";
    
    [self setupNavBackButton];
    
    
    
}

- (void)setupMaskView
{
    UIView *mask = [[UIView alloc] init];
    _maskView = mask;
    
    // mask.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3].CGColor;
    // mask.layer.borderWidth = kScanWindowY;
    
    mask.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    
    mask.bounds = CGRectMake(0, 0, self.view.sd_width , self.view.sd_height - 64.0 );
    mask.center = CGPointMake(self.view.sd_width * 0.5, (self.view.sd_height - 64.0) * 0.5);
    mask.sd_y = 0;
    [self.view addSubview:mask];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.fillRule = kCAFillRuleEvenOdd;
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, self.view.sd_width, (self.view.sd_height - 64.0))];
    
    // MARK: circlePath
    [path appendPath:[UIBezierPath bezierPathWithRect:CGRectMake((self.view.sd_width  -  kScanWindowW)/2, kScanWindowY, kScanWindowW, kScanWindowW)]];
    
    shapeLayer.path = path.CGPath;
    [mask.layer setMask:shapeLayer];
    
    UILabel *label = [[UILabel alloc]init];
    label.numberOfLines = 1; // 需要把显示行数设置成无限制
   // label.font = SystemVersion < 9.0 ? [UIFont systemFontOfSize:ScaleFontForScreen(14)] :[UIFont fontWithName:@"PingFangSC-light" size:ScaleFontForScreen(14)];
    label.font = [UIFont fontWithName:FONT_NAME size:14];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"将二维码放入框中，即可扫描";
    CGSize size =  [self sizeWithString:label.text font:label.font];
    label.bounds = CGRectMake(0, 0, size.width, size.height);
    label.center =CGPointMake(self.view.sd_width * 0.5 ,kScanWindowY + kScanWindowW +20.0);
    
    
    
    [self.view addSubview:label];
}
- (CGFloat)labelWidth
{
    
    return 200.0;
    
}
// 定义成方法方便多个label调用 增加代码的复用性
- (CGSize)sizeWithString:(NSString *)string font:(UIFont *)font
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake([self labelWidth], 2000)//限制最大的宽度和高度
                                       options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin//采用换行模式
                                    attributes:@{NSFontAttributeName: font}//传人的字体字典
                                       context:nil];
    
    return rect.size;
}
- (void)setupBottomBar
{
    UIView *bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.sd_height * 0.9, self.view.sd_width, self.view.sd_height * 0.1)];
    bottomBar.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
    [self.view addSubview:bottomBar];
}

- (void)setupScanWindowView
{
    CGFloat scanWindowH = kScanWindowW;
    CGFloat scanWindowW = kScanWindowW;
    CGFloat scanWindowX = (self.view.sd_width  -  kScanWindowW)/2;
    
    
    UIView *scanWindow = [[UIView alloc] initWithFrame:CGRectMake(scanWindowX, kScanWindowY, kScanWindowW, kScanWindowW)];
    scanWindow.clipsToBounds = YES;
    [self.view addSubview:scanWindow];
    
    CGFloat scanNetImageViewH = 241;
    CGFloat scanNetImageViewW = scanWindow.sd_width;
    UIImageView *scanNetImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan_net"]];
    scanNetImageView.frame = CGRectMake(0, -scanNetImageViewH, scanNetImageViewW, scanNetImageViewH);
    CABasicAnimation *scanNetAnimation = [CABasicAnimation animation];
    scanNetAnimation.keyPath = @"transform.translation.y";
    scanNetAnimation.byValue = @(scanWindowH);
    scanNetAnimation.duration = 1.0;
    scanNetAnimation.repeatCount = MAXFLOAT;
    [scanNetImageView.layer addAnimation:scanNetAnimation forKey:nil];
    [scanWindow addSubview:scanNetImageView];
    
    CGFloat buttonWH = 18;
    
    
    UIButton *topLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWH, buttonWH)];
    [topLeft setImage:[UIImage imageNamed:@"scan_1"] forState:UIControlStateNormal];
    [scanWindow addSubview:topLeft];
    
    UIButton *topRight = [[UIButton alloc] initWithFrame:CGRectMake(scanWindowW - buttonWH, 0, buttonWH, buttonWH)];
    [topRight setImage:[UIImage imageNamed:@"scan_2"] forState:UIControlStateNormal];
    [scanWindow addSubview:topRight];
    
    UIButton *bottomLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, scanWindowH - buttonWH, buttonWH, buttonWH)];
    [bottomLeft setImage:[UIImage imageNamed:@"scan_3"] forState:UIControlStateNormal];
    [scanWindow addSubview:bottomLeft];
    
    UIButton *bottomRight = [[UIButton alloc] initWithFrame:CGRectMake(topRight.sd_x, bottomLeft.sd_y, buttonWH, buttonWH)];
    [bottomRight setImage:[UIImage imageNamed:@"scan_4"] forState:UIControlStateNormal];
    [scanWindow addSubview:bottomRight];
}

- (void)beginScanning
{
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if (!input) return;
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    output.rectOfInterest = CGRectMake((kScanWindowY )/self.view.sd_height, (self.view.sd_width - kScanWindowW)/2/self.view.sd_width, kScanWindowW/self.view.sd_height, kScanWindowW/self.view.sd_width);
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //初始化链接对象
    _session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [_session addInput:input];
    [_session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    //开始捕获
    [_session startRunning];
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        
        NSLog(@"%@",metadataObject.stringValue);
        

        [_session stopRunning];
        //解析扫码数据为
        NSArray *resultAry = [self checkOrderScanString:metadataObject.stringValue];
        
        /**
         *  正常数据格式为 discountCode|orderID
         */
        if(resultAry)
        {
            
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            [self.scanPayEngine getOrderInfo:@{@"orderID": resultAry[1],@"discountCode":resultAry[0],@"payType":kPayTypeOfScan}];
        }else{
            [self.view makeToast:@"您扫描的二维码有误"];
            [_session startRunning];
        }
        
    }
}

- (NSArray *)checkOrderScanString:(NSString *)result
{
    NSArray *array = nil;
    if (result.length) {
        if ([result containsString:@"|"] &&[[result componentsSeparatedByString:@"|"] count] == 2) {
            array = [result componentsSeparatedByString:@"|"];
        }
    }
    
    return array;
}
#pragma mark - Call back
//获取扫描信息回调
- (void)getScanOrderInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserAccountInfoEngine getAccoutInfo];
        

    }else{
        [self.session startRunning];
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
- (void)getUserAccountInfoFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        NSLog(@"%@",messageDic[@"result"]);
        
        if (!messageDic[@"result"][@"cardList"] ) {
            
            UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"您还未绑定银行卡，无法消费，请立即绑定银行卡" andBlock:^(UIAlertAction *action ) {
                ////NSLog(@"%@",action.title);
                if ([action.title isEqualToString:@"好的"]) {
                    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"BankCard" bundle:nil];
                    if ([messageDic[@"result"][@"initPay" ] isEqualToString:@"true"]) {
                        
                        //初次设置支付密码
                        [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"AddCardFirstInputPasswordController"] animated:YES];
                        
                    }else{
                        [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"AddCardCheckPasswordViewController"] animated:YES];
                        
                    }
                }else{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }
                
            } type:@"confirmAndCancel"];
            [self presentViewController:x animated:YES completion:nil];
            
            
        }else{
            
            /**
             *  跳转扫描后订单信息显示界面，用户可确认支付或放弃支付
             */
            UIStoryboard *storyB = [UIStoryboard storyboardWithName:@"ScanCode" bundle:nil];
            
            ScanPayViewController *payView = (ScanPayViewController *)[storyB instantiateViewControllerWithIdentifier:@"ScanPayViewController"];
            payView.delegate = self;
            payView.scanPayEngine = self.scanPayEngine;
            
            payView.cardListInfo = messageDic[@"result"];
            payView.orderInfo = [payView.scanPayEngine.orderInfo mutableCopy];
            
            payView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            payView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
            
            
            [self presentViewController:payView animated:YES completion:^{NSLog(@"finish");}];
        }
        
        
        

    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
//验证支付密码回调
- (void)verifyPayPasswordFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.scanPayEngine payScanOrder:messageDic[@"result"]];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}
//支付订单回调
- (void)payScanOrderFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        self.paymentFinishInfo = messageDic[@"result"];
        
        UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"成功支付订单" andBlock:^(UIAlertAction *action ) {
            if ([action.title isEqualToString:@"好的"]) {
               // [self.navigationController popToRootViewControllerAnimated:YES];
                
                [self performSegueWithIdentifier:@"ShowPayFinishFromScan" sender:self];
                
            }
            
        }  type:@"confirm"];
        [self presentViewController:x animated:YES completion:nil];
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}

- (void)getUserInfoFinish:(NSNotification*) notification
{
    
    [YuNetworkStatusUtilities dismissHUD];
    
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        
        NSString *payAmount = self.scanPayEngine.orderInfo[@"payAmt"];
        NSString *value = ServerMoneyToShow(payAmount);
        NSString *limit = [YuUserDefaultsUtilities stringWithKey:@"UserPayLimit"];
        if(limit.length && ![limit isEqualToString:@"0"] && [limit integerValue] >= [value integerValue])
        {
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            
            [self.scanPayEngine payScanOrderwithCard];
        }else{
            self.tradeView =  [[ZCTradeView alloc] initWithTitle:@"请确认支付信息并输入支付密码" andStyle:ZCPresentStyle];
            self.tradeView.delegate = self;
            [self.tradeView showInView:self.view];
        }
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
}
#pragma mark - 确认支付后弹出 支付密码输入 验证
- (void)cancelBtnClick:(BOOL)isConfirm
{
    [self viewWillAppear:YES];
}
- (void)okBtnClick:(BOOL)isConfirm
{

    NSString *payAmount = self.scanPayEngine.orderInfo[@"payAmt"];
    NSString *value = ServerMoneyToShow(payAmount);
    NSString *limit = [YuUserDefaultsUtilities stringWithKey:@"UserPayLimit"];
    if(limit.length && ![limit isEqualToString:@"0"] && [limit integerValue] >= [value integerValue])
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        
        [self.scanPayEngine payScanOrderwithCard];
    }else if (!limit.length)
    {
        [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
        [self.getUserDetailInfoEngine getUserInfo];
    }else{
        self.tradeView =  [[ZCTradeView alloc] initWithTitle:@"请确认支付信息并输入支付密码" andStyle:ZCPresentStyle];
        self.tradeView.delegate = self;
        [self.tradeView showInView:self.view];
    }
    
    
}
-(NSString *)finish:(NSString *)pwd{
    NSLog(@"haha %@",pwd);
    
    // [self.passwordAndInfos setObject:pwd forKey:@"checkpassword"];
    
    
    return pwd;
}
-(NSString *)finish:(NSString *)pwd confirm:(BOOL)isConfirm
{
    [self.tradeView cancle];
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.verifyPayPasswordEngine verifyPayPassword:pwd];
    
   // self.shadowView.hidden = NO;
   // self.finishView.hidden = NO;
    return pwd;
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getScanOrderInfoFinish:) name:@"GetScanOrderInfoFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserAccountInfoFinish:) name:@"GetUserAccountInfoFinish" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(verifyPayPasswordFinish:) name:@"VerifyPayPasswordFinish" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payScanOrderFinish:) name:@"PayScanOrderFinish" object:nil];
    
   // [self setupScanWindowView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserInfoFinish:) name:@"GetUserInfoFinish" object:nil];
    
    if (self.session && !self.session.isRunning) {
        [self.session startRunning];
    }
    
    
    if (self.isFromAddCardFinish) {
        [self getAccountInfo];
    }
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetScanOrderInfoFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserAccountInfoFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VerifyPayPasswordFinish" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PayScanOrderFinish" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserInfoFinish" object:nil];
}

- (void)getAccountInfo
{
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.getUserAccountInfoEngine getAccoutInfo];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"ShowPayFinishFromScan"]) {
        ScanPayFinishInfoController *controller =  (ScanPayFinishInfoController *)[segue destinationViewController];
        controller.scanPayEngine = self.scanPayEngine;
        controller.paymentFinishInfo = self.paymentFinishInfo;
        
    }
}


@end
